package com.levi.juc.common_class;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

/**
 * CountDownLatch  减法计数器
 * 实际业务中：用于一些必须执行完的任务，等待这些任务执行完再继续往下执行
 */
public class CountDownLatchTest {
    public static void main(String[] args) throws InterruptedException {
        //创建一个countDownLatch对象，初始值是6
        CountDownLatch countDownLatch = new CountDownLatch(6);
        for (int i = 1; i <= 6; i++) {
            new Thread(() -> {
                //计数-1
                System.out.println(Thread.currentThread().getName()+"***");
                countDownLatch.countDown();

            },String.valueOf(i)).start();
        }

        //等待计数归零之后在继续往下执行
        countDownLatch.await();
        System.out.println("结束");

        CountDownLatch countDownLatch1 = new CountDownLatch(7);
        for (int i = 0; i < 5; i++) {
            int finalI = i;
            new Thread(()->{
                countDownLatch1.countDown();
                System.out.println("第二轮开始>>>>> "+ finalI);
            }).start();
        }
        //如果上面的任务没有执行完成（没有减到0），等待3秒之后再往下执行
        countDownLatch1.await(3, TimeUnit.SECONDS);
        System.out.println("countDown1 over!!!");


        CountDownLatch countDownLatch2 = new CountDownLatch(5);
        for (int i = 0; i < 5; i++) {
            final int F = i;
            new Thread(()->{
                countDownLatch2.countDown();
                System.out.println("第三轮:>>>>> "+F);
            }).start();
        }
        countDownLatch2.await();
        System.out.println("第三轮main执行");
    }


}
